import sys
import os
from NearestString import NearestString
from FilenameParser import parser1
from Episode import EpisodeInfo

class UnknownSeries(Exception): pass

series_paths = [ '/media/storage/video/series'
               , '/media/storage/video/series/GordonRamsay'
               ]

class Librarian(object):
  def __init__(self, series_paths):
    known_series = []
    for path in series_paths:
      p = [    ( s, os.path.join(path,s) ) 
          for  s
          in   os.listdir(path) 
          if   os.path.isdir(os.path.join(path,s)) 
          and  not s.startswith('.')
          ]
      known_series.extend(p)
    self.series_locations = dict(known_series)
    # Set up a NN classifier for series names
    self.series_classifier = NearestString(self.series_locations)
    self.filename_parser = parser1()

  def find_shelf(self, episode_info):
    assert isinstance(episode_info, EpisodeInfo)
    nearest_series = self.series_classifier(episode_info.series_name)
    episode_info.series_name = nearest_series
    target_dir = os.path.join( self.series_locations[nearest_series]
                              , "S%d" % episode_info.series_number
                              )
    return target_dir

def files_list(base_path, extensions = ['avi']):
  if os.path.isdir(base_path):
    # Recurse
    all_files = []
    for file in os.listdir(base_path):
      try:
        all_files.extend(files_list(os.path.join(base_path, file), extensions))
      except OSError:
        # Skip the file if we are not allowed to read it
        pass
    return all_files
  else:
    extension = base_path.split('.').pop()
    if extension in extensions:
      return [base_path]
    else:
      return []

verbose = True
simulate = False 

def create_directory(path):
  if verbose:
    print "Create directory:", path
  if not simulate:
    os.mkdir(path)

def move(src,dst):
  if verbose:
    print "Move src:", file 
    print "     dst:", target_file 
    print
  if not simulate:
    os.rename(src,dst)

if __name__ == "__main__":
  librarian = Librarian(series_paths)

  print "Shelving",  sys.argv[1]
  path  = sys.argv[1]
  try:
    files = files_list(path)
  except OSError:
    print "Unable to read", path
    sys.exit(1)
  for file in files:
    try:
      target_dir = librarian.find_shelf(file)
    except UnknownSeries:
      # Skip files we don't know how to shelve
      continue 
    if not os.path.exists(target_dir):
      create_directory(target_dir)
    elif not os.path.isdir(target_dir):
      print "Not a directory:", target_dir

    target_file = os.path.join(target_dir, os.path.basename(file))
    print file,"----->",target_file
    #move(file, target_file)
